import json

import requests

from gupiao.code_info import generate_info, read_csv

header = {
	"Host": "stock.xueqiu.com",
	"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0",
	"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
	"Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
	"Accept-Encoding": "gzip, deflate, br",
	"Connection": "keep-alive",
	"Cookie": "Hm_lvt_1db88642e346389874251b5a1eded6e3=1633609175,1634451369,1635777499; device_id=f22a9f054403c0c6987cc97218f511d7; s=cp19vaih1o; bid=12f6cbd38037025574fa6c0b4111476f_kqaaqsph; xq_a_token=87397660f9d0893a50ec8461b8544612e877c6d5; xqat=87397660f9d0893a50ec8461b8544612e877c6d5; xq_r_token=a5352df548f3835293a625883fdc15af94c6655e; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOi0xLCJpc3MiOiJ1YyIsImV4cCI6MTYzNzE3MjM1OSwiY3RtIjoxNjM1Nzc3NDg4Nzk1LCJjaWQiOiJkOWQwbjRBWnVwIn0.BeBjW7CpeJ4U4zlyYIQ7tJssPjSY7S2Ru9Ezg7rza8V7PE_P9p31G0KZhzMpF4Dh8iKJoRcCsz5K0C4pjfvcckcVGXro-7mce06pleOnCdFv1lpkPcZlKUa77lESEwniwnC2hWcsR5s_OUbUAFniFR0SslEdl3ZQIUeBYOca9vJUgoZSlRA_tY9qhydyADW2mJbtOR6Q4g08maWXm83PBCIM5Arlzt_VW6ayfYZmCph0sllEc_gsQzYSwUmphBEmruRIQBlJR1oWHaWsUXXOgNVLHi0KcP36ngXBdq5APa3-tCST6QxsCiXHMYx08qZxhm2_NKKvgH8OS4WV7ojOYg; u=831635777498358; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1635777940",
	"Upgrade-Insecure-Requests": "1",
	"Sec-Fetch-Dest": "document",
	"Sec-Fetch-Mode": "navigate",
	"Sec-Fetch-Site": "none",
	"Sec-Fetch-User": "?1",
	"Pragma": "no-cache",
	"Cache-Control": "no-cache"
}

def random_sleep():
    import time
    import random
    time.sleep(random.random() * 5 + 0)

def select_data():
    data = read_csv('output-2021-09-09.csv')
    # print(data)
    code_list = []
    for row in data:
        code_list.append(row[0])
    return code_list

def get_top10(code):

    url = 'https://stock.xueqiu.com/v5/stock/f10/cn/top_holders.json?symbol=' + code
    # print(url)
    resp = requests.get(url, timeout=30, headers=header)
    res = str(resp.text)
    data = json.loads(res)
    return data


if __name__ == '__main__':
    code_list = select_data()
    print(len(code_list))
    dict1 = generate_info()

    count = 0
    for code in code_list:
        tmp = get_top10(code)
        top10_details = tmp['data']['items']
        for item in top10_details:
            holder_name = str(item['holder_name'])
            held_ratio = int(item['held_ratio'])
            if(held_ratio > 0 and (holder_name.startswith('中央汇金') or holder_name.startswith('中国证券金融'))):
                print(code, dict1[code], str(item))
    if count % 10 == 0:
        random_sleep()
